package com.example.helloworldtext2.adapter;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;

import com.example.helloworldtext2.R;
import com.example.helloworldtext2.holder.HomeViewHolder;
import com.example.helloworldtext2.model.Article;

import java.util.List;

public class HomeAdapter extends RecyclerView.Adapter<HomeViewHolder> {
    private List<Article> articleList;
    private StaggeredGridLayoutManager layoutManager;

    public HomeAdapter(StaggeredGridLayoutManager layoutManager, List<Article> articleList) {
        this.layoutManager = layoutManager;
        this.articleList = articleList;
        // 设置LayoutManager不随着item的更新而自动滚动
        if (layoutManager != null) {
            layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        }
    }
    
    @NonNull
    @Override
    public HomeViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_article, parent, false);
        return new HomeViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull HomeViewHolder holder, int position) {
        Article article = articleList.get(position);
        Log.d("sdfsd", "首页瀑布流数据"+ article.getTitle());
        holder.bind(article);
        
        // 防止瀑布流布局回流抖动
        ViewGroup.LayoutParams layoutParams = holder.itemView.getLayoutParams();
        if (layoutParams instanceof StaggeredGridLayoutManager.LayoutParams) {
            StaggeredGridLayoutManager.LayoutParams staggeredParams = 
                (StaggeredGridLayoutManager.LayoutParams) layoutParams;
            // 设置不完整项防止布局跳动
            staggeredParams.setFullSpan(false);
        }
    }

    @Override
    public int getItemCount() {
        return articleList.size();
    }
    
    // 添加数据时使用此方法，避免整个列表刷新
    public void addArticles(List<Article> newArticles) {
        if (newArticles == null || newArticles.isEmpty()) {
            return;
        }
        
        int startPosition = articleList.size();
        articleList.addAll(newArticles);
        Log.d("HomeAdapter", "Adding " + newArticles.size() + " articles at position " + startPosition);
        notifyItemRangeInserted(startPosition, newArticles.size());
    }
    
    // 禁用默认的动画变化，防止布局跳动
    @Override
    public void onAttachedToRecyclerView(@NonNull RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
        RecyclerView.ItemAnimator itemAnimator = recyclerView.getItemAnimator();
        if (itemAnimator != null) {
            itemAnimator.setChangeDuration(0);
            itemAnimator.setMoveDuration(0);
            itemAnimator.setAddDuration(0);
            itemAnimator.setRemoveDuration(0);
        }
    }
}